package com.bsoft.hospitalchs.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.widget.EditText;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Tools {

    public static <T> List<T> getLastElements(ArrayList<T> list, int nbElems) {
        return list.subList(Math.max(list.size() - nbElems, 0), list.size());
    }

    public static Long getLong(Cursor c, String col) {
        return c.getLong(c.getColumnIndex(col));
    }

    public static int getInt(Cursor c, String col) {
        return c.getInt(c.getColumnIndex(col));
    }

    public static String getString(Cursor c, String col) {
        return c.getString(c.getColumnIndex(col));
    }

    public static boolean getBoolean(Cursor c, String col) {
        return getInt(c, col) == 1;
    }

    public static Date getDateSeconds(Cursor c, String col) {
        return new Date(Long.parseLong(Tools.getString(c, col)) * 1000);
    }

    public static Date getDateMilliSeconds(Cursor c, String col) {
        return new Date(Long.parseLong(Tools.getString(c, col)));
    }

    public static boolean isInt(String value) {
        try {
            // modify by sun
            Long.parseLong(value);
            return true;
        } catch (NumberFormatException nfe) {
        }
        return false;
    }

    public static Boolean parseBool(String value) {
        Boolean res = null;
        if (value.compareToIgnoreCase("true") == 0) {
            res = true;
        } else if (value.compareToIgnoreCase("false") == 0) {
            res = false;
        }
        return res;
    }

    public static Integer parseInt(String value) {
        Integer res = null;
        try {
            res = Integer.parseInt(value);
        } catch (Exception e) {
        }

        return res;
    }

    public static Integer parseInt(String value, Integer defaultValue) {
        Integer res = defaultValue;
        try {
            res = Integer.parseInt(value);
        } catch (Exception e) {
        }

        return res;
    }

    @SuppressLint("SimpleDateFormat")
    public static Date parseDate(String dateStr) {
        try {
            String pattern = "yyyy-MM-dd HH:mm";
            if (dateStr.length() == 10)
                pattern = "yyyy-MM-dd";
            else if (dateStr.length() == 16)
                pattern = "yyyy-MM-dd HH:mm";
            else if (dateStr.length() == 19)
                pattern = "yyyy-MM-dd HH:mm:ss";

            return new SimpleDateFormat(pattern).parse(dateStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 格式化日期
     *
     * @param date
     * @return
     */
    @SuppressLint("SimpleDateFormat")
    public static String formatDate(Date date) {
        return formatDateTime(date, "yyyy-MM-dd HH:mm");
    }

    /**
     * 判断是否是闰年
     *
     * @param year
     * @return
     */
    public static boolean isLeapYear(int year) {

        return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0);
    }

    /**
     * 格式化日期时间
     *
     * @param date
     * @return
     */
    @SuppressLint("SimpleDateFormat")
    public static String formatDateTime(Date date, String format) {
        try {
            return new SimpleDateFormat(format).format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取指定范围内的随机整数
     *
     * @param minVal
     * @param maxVal
     * @return
     */
    public static int getRandomInt(int minVal, int maxVal) {
        Random rand = new Random();
        int tmp = Math.abs(rand.nextInt());
        return tmp % (maxVal - minVal + 1) + minVal;
    }

    public static int getMinNonNeg(int... x) {
        int min = Integer.MAX_VALUE;
        for (int i : x) {
            if (i >= 0 && i < min)
                min = i;
        }
        return min;
    }

    private static String getAppBaseDir(Context ctx) {
        String filesDir = ctx.getFilesDir().toString();
        int index = filesDir.indexOf("/files");
        return filesDir.substring(0, index);
    }

    public static String getSharedPrefDir(Context ctx) {
        return getAppBaseDir(ctx) + "/shared_prefs";
    }

    public static String shortenString(String s) {
        if (s.length() > 20) {
            return s.substring(0, 20);
        } else {
            return s;
        }
    }

    public static String getTextValue(EditText text) {
        return text.getText().toString();
    }

    /**
     * 从ResponseEntity中提取错误信息
     *
     * @param
     * @return
     */
    /*public static String getErrorMessage(ResponseEntity entity) {
        String msg = GlobalVars.getContext().getString(R.string.pub_network_error);
		if (entity != null && !TextUtils.isEmpty(entity.getErrorMessage()))
			msg = entity.getErrorMessage();
		return msg;
	}*/
    public static String getJsonString(JSONObject json, String key) {
        String value = "";
        if (json.has(key)) {
            try {
                value = json.getString(key);
            } catch (JSONException e) {
            }
        }
        return value;
    }

    public static int getJsonInt(JSONObject json, String key) {
        int value = 0;
        if (json.has(key)) {
            try {
                value = json.getInt(key);
            } catch (Exception e) {
            }
        }
        return value;
    }

    public static long getJsonLong(JSONObject json, String key) {
        long value = -1;
        if (json.has(key)) {
            try {
                value = json.getLong(key);
            } catch (Exception e) {
            }
        }
        return value;
    }

    public static float getJsonFloat(JSONObject json, String key) {
        float value = 0f;
        if (json.has(key)) {
            try {
                value = Float.parseFloat(json.getString(key));
            } catch (Exception e) {
            }
        }
        return value;
    }

    public static boolean getJsonBoolean(JSONObject json, String key) {
        return getJsonBoolean(json, key, false);
    }

    public static boolean getJsonBoolean(JSONObject json, String key, boolean defaultVal) {
        boolean value = defaultVal;
        if (json.has(key)) {
            try {
                value = json.getBoolean(key);
            } catch (Exception e) {
            }
        }
        return value;
    }

    public static JSONArray getJsonArray(JSONObject json, String key) {
        JSONArray value = null;
        if (json.has(key)) {
            try {
                value = json.getJSONArray(key);
            } catch (JSONException e) {
            }
        } else {
            value = new JSONArray();
        }
        return value;
    }

    public static JSONObject getJsonObject(JSONObject json, String key) {
        JSONObject result = null;
        if (json.has(key)) {
            try {
                result = json.getJSONObject(key);
            } catch (JSONException e) {
            }
        }
        return result;
    }

    public static JSONObject getJsonObject(JSONArray arr, int index) {
        JSONObject result = null;
        try {
            result = arr.getJSONObject(index);
        } catch (JSONException e) {
        }
        return result;
    }

    /**
     * 根据当前时间来计算任务的剩余天数
     *
     * @param endDate
     * @return add by sun
     */
    public static int getRemainDays(String endDate) {
        long millisDiff = Tools.parseDate(endDate).getTime() - System.currentTimeMillis();
        return getDayCountByMillis(millisDiff);
    }

    /**
     * 计算两个日期之间的天数
     *
     * @param fromDate
     * @param toDate
     * @return
     */
    public static int getDayCount(String fromDate, String toDate) {
        long millisDiff = Tools.parseDate(toDate).getTime() - Tools.parseDate(fromDate).getTime();
        return getDayCountByMillis(millisDiff);
    }

    public static int getDayCount(String fromDate, long toDateMillis) {
        long millisDiff = toDateMillis - Tools.parseDate(fromDate).getTime();
        return getDayCountByMillis(millisDiff);
    }

    /**
     * 根据时间差（毫秒）计算相差天数
     *
     * @param timeDiff
     * @return
     */
    private static int getDayCountByMillis(long timeDiff) {
        int result = 0;
        int c = timeDiff < 0 ? -1 : 1;
        long millisOfDay = (24 * 1000 * 3600);
        // 相差不到24小时
        if (Math.abs(timeDiff) < millisOfDay) {
            result = 1; // 不足24小时算一天
        } else {
            result = (int) (Math.abs(timeDiff) / millisOfDay) + (Math.abs(timeDiff) % millisOfDay > 0 ? 1 : 0);
        }
        return result * c;
    }

    /**
     * 判断是否存在SDCARD 2014-10-10 张晓光
     *
     * @return true 存在 false 不存在
     */
    public static Boolean sdcardIsExist() {
        String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 转成base
     *
     * @param path
     * @return
     * @throws Exception
     */
    public static String encodeBase64File(String path) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return Base64.encodeToString(buffer, Base64.DEFAULT);
    }

    /**
     * 转换手机号码格式，如果返回null，则不是手机号
     *
     * @param str
     * @return
     */
    public static String getAvailableMobile(String str) {
        // 先去掉空格
        str = str.replace(" ", "");
        if (str.startsWith("+86"))
            str = str.substring(3);
        // 如果是11为数字，直接返回
        if (str.length() == 11 && TextUtils.isDigitsOnly(str) && str.startsWith("1"))
            return str;

        return null;
    }

    /**
     * 判断是否是11位手机号码
     *
     * @param str
     * @return
     */
    public static boolean isAvailableMobile(String str) {
        return str != null && str.length() == 11 && TextUtils.isDigitsOnly(str) && str.startsWith("1");
    }

    public static int getScreenWidth(Activity activity) {
        return getDisplayMetrix(activity).widthPixels;
    }

    public static int getScreenHeight(Activity activity) {
        return getDisplayMetrix(activity).heightPixels;
    }

    public static DisplayMetrics getDisplayMetrix(Activity activity) {
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm;
    }

    /**
     * 判断密码是否为合格密码
     * <p/>
     * 不为空，并且在8到16位
     *
     * @param str
     * @return
     */
    public static boolean isAvailablePassword(String str) {
        return !TextUtils.isEmpty(str) && str.length() >= 6 && str.length() <= 16;
    }

    /**
     * 判断是否是一个合法的密码
     */
    public static boolean isPassword(String password) {
        Pattern p = Pattern
                .compile("^[A-Za-z0-9]+$");
        Matcher m = p.matcher(password);
        return m.matches();
    }

    /**
     * 判断是否是一个合法的手机号
     *
     * @param mobiles String类型的手机号码
     * @return true 是一个合法的手机号 <br>
     * false 不是一个合法的手机号
     */
    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern
                .compile("^((13[0-9])|(14[0-9])|(17[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    /**
     * 判断验证码为合格的验证码
     * <p/>
     * 不为空，并且是6位纯数字
     *
     * @param str
     * @return
     */
    public static boolean isAvailableCode(String str) {
        return !TextUtils.isEmpty(str) && str.length() == 6 && TextUtils.isDigitsOnly(str);
    }

    /**
     * 判断身份证验证码是否为可用身份证号码
     * <p/>
     * 不为空，长度为18，并且前17位必须是数字
     *
     * @param str
     * @return
     */
    public static boolean isAvailableIdCard(String str) {
        return !TextUtils.isEmpty(str) && str.length() == 18 && TextUtils.isDigitsOnly(str.substring(0, 16));
    }

    public static int dp2px(Context context, int dpValue) {
        return (int) (dpValue * context.getResources().getDisplayMetrics().density);
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public static int getVersion(Context context) {
        int version = 1;
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            version = info.versionCode;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return version;
    }

    /**
     * 获取屏幕宽度
     *
     * @param activity 上下文
     * @return
     */
    public final static int getWindowsWidth(Activity activity) {
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }


    public static int getAge(Date birthDate) {

        if (birthDate == null)
            throw new
                    RuntimeException("出生日期不能为null");

        int age = 0;

        Date now = new Date();

        SimpleDateFormat format_y = new
                SimpleDateFormat("yyyy");
        SimpleDateFormat format_M = new
                SimpleDateFormat("MM");

        String birth_year =
                format_y.format(birthDate);
        String this_year =
                format_y.format(now);

        String birth_month =
                format_M.format(birthDate);
        String this_month =
                format_M.format(now);

// 初步，估算
        age =
                Integer.parseInt(this_year) - Integer.parseInt(birth_year);

// 如果未到出生月份，则age - 1
        if
                (this_month.compareTo(birth_month) < 0)
            age -=
                    1;
        if (age <
                0)
            age =
                    0;
        return age;
    }

    /**
     * float 转 int
     *
     * @param args0
     * @return
     */
    public static Integer doFloatToInt(Float args0) {
        return args0.intValue() * 100;
    }

    /**
     * String 转 float 转 String
     *
     * @param args0
     * @return
     */
    public static String doStringToFloatToString(String args0) {
        Float arg = Float.parseFloat(args0) / 100F;
        return String.valueOf(arg);
    }

    public static String doStringToFloatToString(Integer args0) {
        Float arg = Float.parseFloat(String.valueOf(args0)) / 100F;
        return String.valueOf(arg);
    }

    public static Float doStringToFloatToStringTen(String args0) {
        Float arg = Float.parseFloat(args0) / 10F;
        return arg;
    }
    /**
     * 检测当的网络（WLAN、3G/2G）状态
     * @param context Context
     * @return true 表示网络可用
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected())
            {
                // 当前网络是连接的
                if (info.getState() == NetworkInfo.State.CONNECTED)
                {
                    // 当前所连接的网络可用
                    return true;
                }
            }
        }
        return false;
    }
}
